angular.module('app')
    .factory('authenFactory', ['apiUrl','$rootScope','$q','$injector',function (apiUrl,$rootScope,$q,$injector) {
    var interceptor = {
        'request': function (request) {
            if(request.url.indexOf(".css")==-1&&
                request.url.indexOf(".html")==-1&&
                request.url.indexOf(".js")==-1){

                request.headers["Authorization"]="Bearer "+app.token;
            }

            // 成功的请求方法
            return request; // 或者 $q.when(config);
        },
        'response' : function(response) {
            //系统500 弹出相应错误
            if(response.data!=undefined&&response.data.code!=undefined&&response.data.code=="5000"){
                $rootScope.$emit("sysNetError", "系统异常:"+response.data.msg);
                return $q.reject(response);
            }else{
                return response;
            }

        },
        responseError: function (response) {
            var status = response.status;
            // 判断错误码，如果是未登录
            if(status == "403"||status == "401"){
                //是否已经发送过延迟请求
                if(app.isErrorSend){
                    app.isErrorSend = false;
                    // 全局事件，方便其他view获取该事件，并给以相应的提示或处理
                    $rootScope.$emit("userIntercepted","notLogin");
                    return $q.reject(response);
                }
                else{
                    return response;
                }
            }
            else if(status == "502"){
                console.log("netError",response.status,response.statusText);
                return response;
            }
            else{
                $rootScope.$emit("netError",response.status,response.statusText);
                return response;
            }
            //return $q.reject(response);
        }
    };
    return interceptor;
}]);